package com.h4313.ghome.io;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.util.Log;

import com.h4313.ghome.model.Temperature;

public class TemperatureTask extends AsyncTask<String, Void, Temperature> {

	public interface TemperatureCallback {
		public void onTemperatureFound(Temperature temp);
	}

	WeakReference<TemperatureCallback> mCallback;

	public TemperatureTask(TemperatureCallback callback) {
		mCallback = new WeakReference<TemperatureCallback>(callback);
	}

	@Override
	protected Temperature doInBackground(String... urls) {

		Temperature tempObj = new Temperature();
		try {

			String contentAsString = NetworkHelper.downloadUrl(urls[0], 20000,
					20000);
			JSONObject root;
			root = new JSONObject(contentAsString);
			double temp = root.getDouble("value");
			Integer id = root.getInt("id_sensor");
			String date = root.getString("date");

			SimpleDateFormat format = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss", Locale.FRANCE);
			Date dateobj = format.parse(date);

			tempObj.setIdCapteur(id);
			tempObj.setTemperature(temp);
			tempObj.setDate(dateobj);
			Log.d("Margot", "okok");
			return tempObj;

		} catch (IOException e) {
			System.out
					.print("Unable to retrieve web page. URL may be invalid.");
			e.printStackTrace();
			return null;
		} catch (JSONException e) {
			e.printStackTrace();
			return null;
		} catch (ParseException e) {
			e.printStackTrace();
			return null;
		}

	}

	@Override
	protected void onPostExecute(Temperature result) {

		if (mCallback.get() != null) {

			mCallback.get().onTemperatureFound(result);
		}
	}

}
